package com.ad.aidai.activitys.feedback;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseActivity;
import com.ad.aidai.bean.OnActivityResultRequestCode;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.common.widgets.photoview.DragPhotoView;
import com.bumptech.glide.Glide;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by pure on 2017/2/14.
 */

public class FeedbackActivity extends BaseActivity implements FeedbackContract.View {

    @BindView(R.id.tv_num_of_feedback_content_text)
    TextView tvNumOfFeedbackContentText;
    @BindView(R.id.et_feedback_content)
    EditText etFeedbackContent;
    @BindView(R.id.et_contact)
    EditText etContact;
    @BindViews({R.id.iv_feedback_image_1, R.id.iv_feedback_image_2, R.id.iv_feedback_image_3})
    ImageView[] ivFeedbackImages;
    @BindView(R.id.iv_feedback_image_add)
    ImageView ivFeedbackImageAdd;
    @BindViews({R.id.fl_feedback_image_1, R.id.fl_feedback_image_2, R.id.fl_feedback_image_3})
    FrameLayout[] flFeedbackImages;

    private FeedbackContract.Presenter mPresenter;

    private NormalDialog dialog;
    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    private LoadingDialog loadingDialog;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_software_feedback);
        ButterKnife.bind(this);

        etFeedbackContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvNumOfFeedbackContentText.setText(charSequence.length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        new FeedbackPresenter(this, this).subscribe();

        mBasIn = new BounceTopEnter();
        mBasOut = new SlideTopExit();

    }

    @Override
    public void setPresenter(FeedbackContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick({R.id.iv_back, R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                exit();
                break;
            case R.id.tv_submit:
                if(checkEdit()){
                    toast("请填写反馈内容");
                }else{
                    mPresenter.submit(etFeedbackContent.getText().toString(),etContact.getText().toString()
                            ,mPresenter.getAddedImage());
                }
                break;
        }
    }

    @OnClick({R.id.iv_feedback_image_1, R.id.iv_feedback_image_d1, R.id.iv_feedback_image_2,
            R.id.iv_feedback_image_d2, R.id.iv_feedback_image_3, R.id.iv_feedback_image_d3,
            R.id.iv_feedback_image_add})
    public void onClickImage(View view) {
        switch (view.getId()) {
            case R.id.iv_feedback_image_1:
                DragPhotoView.startDragPhotoActivity(this, ivFeedbackImages[0], mPresenter.getImageUrl(0));
                break;
            case R.id.iv_feedback_image_d1:
                mPresenter.deleteImage(0);
                break;
            case R.id.iv_feedback_image_2:
                DragPhotoView.startDragPhotoActivity(this, ivFeedbackImages[1], mPresenter.getImageUrl(1));
                break;
            case R.id.iv_feedback_image_d2:
                mPresenter.deleteImage(1);
                break;
            case R.id.iv_feedback_image_3:
                DragPhotoView.startDragPhotoActivity(this, ivFeedbackImages[3], mPresenter.getImageUrl(3));
                break;
            case R.id.iv_feedback_image_d3:
                mPresenter.deleteImage(2);
                break;
            case R.id.iv_feedback_image_add:
                addImage();
                break;
        }
    }

    @Override
    public void showFeedbackImage(String... urls) {
        int position = 0;
        ivFeedbackImageAdd.setVisibility(View.VISIBLE);
        for (String url : urls) {
            flFeedbackImages[position].setVisibility(View.GONE);
            if (!CheckUtil.checkStrNull(url)) {
                Glide.with(this)
                        .load(url)
                        .placeholder(R.mipmap.default_image)
                        .dontAnimate()
                        .into(ivFeedbackImages[position]);
                flFeedbackImages[position].setVisibility(View.VISIBLE);
                position++;
                if (position >= 3) {
                    ivFeedbackImageAdd.setVisibility(View.GONE);
                    break;
                }
            }
        }
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("提交中...")
                .setFailedText("提交失败")
                .setSuccessText("提交成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void closeActivity() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        FeedbackActivity.this.finish();
                    }
                });
            }
        }).start();

    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit(){
        if(checkEdit()){
            FeedbackActivity.this.finish();
        }else{
            back();
        }
    }

    private void back() {
        if (dialog == null) {
            dialog = new NormalDialog(this);
            dialog.content("反馈未提交，确认离开？")
                    .style(NormalDialog.STYLE_TWO)
                    .titleTextSize(20)
                    .btnText("确定", "取消")
                    .showAnim(mBasIn)
                    .dismissAnim(mBasOut);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (dialog.isShowing()) {
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        FeedbackActivity.this.finish();
                                    }
                                });
                            }
                        }).start();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == OnActivityResultRequestCode.CHOOSE_STATE_IMAGE) {
                List<ImageItem> images = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                List<String> paths = new ArrayList<>();
                for (int i = 0; i < images.size(); ++i) {
                    paths.add(images.get(i).path);
                }
                mPresenter.addImage(paths);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void addImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);//显示拍照按钮
        imagePicker.setSelectLimit(3 - mPresenter.getImageCount());//选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);//裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);

        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, OnActivityResultRequestCode.CHOOSE_STATE_IMAGE);
    }

    /**
     * 检查是否编辑过
     * @return true---没有编辑过,false---编辑过
     */
    private boolean checkEdit(){
        boolean edit = CheckUtil.checkStrNull(etFeedbackContent.getText().toString())
                &&CheckUtil.checkStrNull(etContact.getText().toString())
                &&(mPresenter.getImageCount()==0);
        return edit;
    }

}
